from flask import render_template, request, current_app, session, redirect, url_for, g, abort, jsonify

from common import user_getter
from info.models import User
from response_code import RET
from . import admin_blue


@admin_blue.route('/index')
@user_getter
def index():
    return render_template("admin/index.html")


@admin_blue.route('/logout')
def logout():
    try:
        session.pop("user_id", None)
        session.pop("nick_name", None)
        session.pop("is_admin", None)
    except Exception as e:
        current_app.logger(e)
        return abort(500)
    return redirect(url_for("admin.login"))


@admin_blue.route('/login', methods=["GET", "POST"])
def login():
    if request.method == "GET":
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)
        if user_id and is_admin:
            return redirect(url_for("admin.index"))
        return render_template("admin/login.html")

    # 获取参数
    # 我们此时可以采取每个请求无论成功还是失败,都渲染失败
    # 渲染模板不需要返回JSON错误,没有JSON我们获取参数就用表单
    username = request.form.get("username")
    password = request.form.get("password")

    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数错误")

    # 查询当前用户
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as e:
        current_app.logger(e)
        return render_template("admin/login.html", errmsg="用户查询失败")

    if not user or not user.check_password(password):
        return render_template("admin/login.html", errmsg="用户名或密码错误")

    # 保存用户的登录信息
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["is_admin"] = user.is_admin

    # 跳转到后面管理首页
    return redirect(url_for("admin.index"))


@admin_blue.route('/')
def login2():
    return redirect(url_for("admin.index"))